package com.yunhe.authority.service.base.impl;

import com.yunhe.authority.repository.base.StationTypeRepository;
import com.yunhe.authority.domain.base.StationType;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.authority.service.base.StationTypeService;
import com.yunhe.common.util.QueryUtil;
import com.yunhe.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 电站类型Service
 * @desc 电站类型服务类实现
 * @author liuronglei
 */
@Service
public class StationTypeServiceImpl implements StationTypeService {
    @Autowired
    private StationTypeRepository stationTypeRepository;

    /**
     * 电站类型对象处理和判断
     * @param siteType 电站类型对象
     */
    private void processBeforeSave(StationType siteType)
            throws ArgumentErrorException, UniqueConstraintsException {
        //判断电站类型代码、编号、标题是否为空
        if (siteType.getCode() == null
                || StringUtil.isEmpty(siteType.getName())
                || StringUtil.isEmpty(siteType.getTitle())) {
            throw new ArgumentErrorException("电站类型代码、编号、标题不能为空");
        }
        //判断单位代码是否已存在
        StationType typeByCode = this.findByCode(siteType.getCode());
        if (typeByCode != null) {
            if (siteType.getId() == null || typeByCode.getId().longValue() != siteType.getId().longValue()) {
                throw new UniqueConstraintsException("该电站类型代码已存在");
            }
        }
        //判断单位编号是否已存在
        StationType typeByName = this.findByName(siteType.getName());
        if (typeByName != null) {
            if (siteType.getId() == null || typeByName.getId().longValue() != siteType.getId().longValue()) {
                throw new UniqueConstraintsException("该电站类型编号已存在");
            }
        }
        //如果序号为空，则默认为代码
        if (StringUtil.isEmpty(siteType.getSn()) && siteType.getCode() != null) {
            siteType.setSn(String.valueOf(siteType.getCode()));
        }
    }

    /**
     * 新增电站类型
     * @param siteType 电站类型对象
     */
    @Override
    @Transactional
    public StationType createStationType(StationType siteType)
            throws ArgumentErrorException, UniqueConstraintsException {
        siteType.setId(null);
        processBeforeSave(siteType);
        return stationTypeRepository.save(siteType);
    }

    /**
     * 删除电站类型
     * @param siteTypeId 电站类型ID
     */
    @Override
    @Transactional
    public void deleteStationType(Long siteTypeId) {
        stationTypeRepository.deleteById(siteTypeId);
    }

    /**
     * 更新电站类型（更新全部字段）
     * @param siteType 电站类型对象
     */
    @Override
    @Transactional
    public StationType updateStationType(StationType siteType)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        boolean exists = siteType.getId() != null && stationTypeRepository.existsById(siteType.getId());
        if (!exists) {
            throw new ObjectNotFoundException("找不到ID为" + siteType.getId() + "的电站类型");
        }
        processBeforeSave(siteType);
        return stationTypeRepository.save(siteType);
    }

    /**
     * 更新电站类型（更新指定字段）
     * @param siteTypeId 电站类型ID
     * @param code 代码
     * @param name 编号
     * @param title 标题
     * @param sn 排序序号
     * @param activity 是否可用
     */
    @Override
    @Transactional
    public StationType updateStationType(Long siteTypeId,
                                         Long code,
                                         String name,
                                         String title,
                                         String sn,
                                         Boolean activity)
            throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        StationType siteType = this.findByStationTypeId(siteTypeId);
        if (siteType == null) {
            throw new ObjectNotFoundException("找不到ID为" + siteType + "的电站类型");
        }
        Optional.ofNullable(code).ifPresent(siteType::setCode);
        Optional.ofNullable(name).ifPresent(siteType::setName);
        Optional.ofNullable(title).ifPresent(siteType::setTitle);
        Optional.ofNullable(sn).ifPresent(siteType::setSn);
        Optional.ofNullable(activity).ifPresent(siteType::setActivity);
        processBeforeSave(siteType);
        return stationTypeRepository.save(siteType);
    }

    /**
     * 根据ID获得电站类型对象
     * @param id 状态ID
     */
    @Override
    public StationType findByStationTypeId(Long id) {
        return stationTypeRepository.findById(id).orElse(null);
    }

    /**
     * 根据代码获得电站类型对象
     * @param code 代码
     */
    @Override
    public StationType findByCode(Long code) {
        return stationTypeRepository.findByCode(code);
    }

    /**
     * 根据编号获得电站类型对象
     * @param name 编号
     */
    @Override
    public StationType findByName(String name) {
        return stationTypeRepository.findByName(name);
    }

    /**
     * 获得全部电站类型对象
     */
    @Override
    public Iterable<StationType> findStationTypes() {
        return stationTypeRepository.findAll(QueryUtil.defaultSort());
    }
}
